package com.atguigu.juc.day02.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo05FairLock {

    // 创建公平锁对象
    private Lock lock = new ReentrantLock(true);

    public void doSth() {
        try {

            lock.lock();

            System.out.println(Thread.currentThread().getName() + " 线程。");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            lock.unlock();

        }
    }

    public static void main(String[] args) {

        Demo05FairLock demo = new Demo05FairLock();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    demo.doSth();
                }
            }, "thread-" + i).start();
        }

    }

}
